package com.zjj.lbw.springbootstu.handwriting.conditional;

import com.zjj.lbw.springbootstu.handwriting.annotation.ZjjConditionalOnClass;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

/**
 * @author zhanglei.zjj
 * @description 根据有没有相关依赖来进行条件装配，例如添加了tomcat依赖就使用tomcat作为web容器，添加了jetty依赖就使用jetty作为web容器
 * @date 2023/6/24 11:10
 */
public class ZjjOnClassCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> annotationAttributes =
                metadata.getAnnotationAttributes(ZjjConditionalOnClass.class.getName());

        String className = (String) annotationAttributes.get("value");

        try {
            context.getClassLoader().loadClass(className);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
}
